<?php
namespace app\model;

/**
 * Author: cbw
 * Desc: 红包发放检测
 * Time: 2022/5/11 15:35
 * Email: 17854288794@163.com
 */
class RedPackValidate{

    static function Base($system,$fans)
    {
        global $_G, $_P;
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $fuid = $_G['member']['uid'];
        $result = array();
        $GLat = $_P['GLat'];
        $GLng = $_P['GLng'];

        if ($config['comm711'] * 100 > 0) {
            $randomfee = floatval(mt_rand(round($config['comm711'] * 100), round($config['comm712'] * 100)) / 100);
        } else {
            $first = intval($config['comm43']);
            $second = $first + intval($config['comm43_2']);
            $gailv = mt_rand(0, 99);
            if ($first == 0 || $first == 100 || $gailv < $first) {
                $randomfee = floatval(mt_rand(round($config['comm41'] * 100), round($config['comm42'] * 100)) / 100);
            } elseif ($gailv < $second && $config['comm42_2'] != 0) {
                $randomfee = floatval(mt_rand(round($config['comm41_2'] * 100), round($config['comm42_2'] * 100)) / 100);
            } elseif ($config['comm42_3'] != 0) {
                $randomfee = floatval(mt_rand(round($config['comm41_3'] * 100), round($config['comm42_3'] * 100)) / 100);
            } else {
                $randomfee = floatval(mt_rand(round($config['comm41'] * 100), round($config['comm42'] * 100)) / 100);
            }
        }

        $ClientIp = $_G['clientip'];
        $data = array(
            'uniacid' => $_G['mpid'],
            'themeid' => $themeid,
            'type' => 7,
            'uid' => $fuid,
            'openid' => $_G['openid'],
            'addtime' => TIMESTAMP,
            'fee' => $randomfee,
            'ip' => $ClientIp,
            'status' => 0,
        );

        $workerid = intval($_P['wid']) > 0 ? intval($_P['wid']) : intval($_P['workerid']);
        $theyworker = Worker::getThemeWorkerByUid($workerid, $themeid, 1);
        if (empty($theyworker)) {
            $workerid = 0;
        } elseif ($theyworker['comm4status'] > 1) {
            $workerid = 0;
        } elseif ($config['comm4typeyg'] > 0) {
            $liulan = 0;
            $chengjiao = 0;
            switch ($config['comm4typeyg']) {
                case '1':
                    $liulan = 30;
                    break;
                case '2':
                    $liulan = 40;
                    break;
                case '3':
                    $liulan = 50;
                    break;
                case '4':
                    $liulan = 60;
                    break;
                case '5':
                    $liulan = 70;
                    break;
                case '6':
                    $chengjiao = 5;
                    break;
                case '7':
                    $chengjiao = 10;
                    break;
                case '8':
                    $chengjiao = 15;
                    break;
                case '9':
                    $chengjiao = 20;
                    break;
                case '10':
                    $chengjiao = 25;
                    break;
                case '11':
                    $chengjiao = 30;
                    break;
                case '12':
                    $chengjiao = 40;
                    break;
                case '13':
                    $chengjiao = 50;
                    break;
            }
            if ($theyworker['forward'] > 500) {
                if ($liulan > 0) {
                    if (($theyworker['forward'] / $theyworker['scansum'] * 100) > $liulan) {
                        db_query("UPDATE " . tablename(t_worker) . " SET comm4status = 2 WHERE uid ='{$workerid}'");
                        $workerid = 0;
                    }

                } elseif ($chengjiao > 0) {
                    $cjtotal = (int)db_fetchcolumn('SELECT COUNT(*) FROM ' . tablename(t_record) . "
					WHERE status > 0 and workerid = '{$workerid}' and themeid = '{$themeid}' ");
                    if ($theyworker['forward'] / $cjtotal > $chengjiao) {
                        db_query("UPDATE " . tablename(t_worker) . " SET comm4status = 2 WHERE uid ='{$workerid}'");
                        $workerid = 0;
                    }
                }
            }
        }

        if (empty($workerid)) {
            $data['msg'] = '没有员工信息，不可领红包';
            $data['status'] = '9';
            $insertid = db_insert(t_commshare, $data);

            $result = array(
                "status" => 5,
                "msg" => '很遗憾,没有摇到~',
            );
            return $result;
        }


        if ($config['iscomm'] == 0 || $system['fenxiao07'] == 0 || $config['comm42'] * 100 == 0) {
            $result = array(
                "status" => 1,
                "msg" => '摇一摇未开启',
            );
            return $result;
        }
        if ($config['locationtype'] == 1 && (empty($GLat) || empty($GLng))) {
            $result['errcode'] = 5;
            $result['msg'] = '没有获得地理位置信息，请打开手机gps，再刷新试试！';
            return $result;
        }

        //获取第几天
        $pm = array(":themeid" => $themeid, ":openid" => $_G['openid']);
        $lightsum = (int)db_fetchcolumn("SELECT COUNT(*) FROM " . tablename(t_share) . "
			WHERE themeid = :themeid and openid = :openid and status = 1", $pm);
        $share = db_find("SELECT * FROM " . tablename(t_share) . "
				WHERE themeid = :themeid and openid = :openid and status = 1
				order by addtime desc ", $pm);
        if (date('Y-m-d') != date('Y-m-d', $share['addtime'])) {
            $lightsum = $lightsum + 1;
        }

        //echo "天数:".$lightsum;
        if ($op == "get") {
            $begintime1 = $theme['begintime'];
            $endime1 = $theme['endtime'];
            if ($begintime1 > TIMESTAMP) {
                $result['errcode'] = 5;
                $result['msg'] = '活动尚未开始，敬请期待~';
                return $result;
            }
            if ($endime1 < TIMESTAMP || $theme['status'] != 1) {
                $result['errcode'] = 5;
                $result['msg'] = '活动已经结束啦，感谢您的支持';
                return $result;
            }

            //失败的提示
            $result['errcode'] = 5;
            $result['msg'] = '很遗憾未摇到,感谢支持!';


            //在服务器别的软件领过的不可以领
            if ($config['comm4dashuju'] == 0) {
                $status = Comm::gethistorycomm($themeid);
                if ($status['error'] == 1) {
                    $data['msg'] = $status['msg'];
                    $data['status'] = '8';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }

            if (empty($config['comm4_time1'])){
                $config['comm4_time1'] =7;
            }
            if (empty($config['comm4_time2'])){
                $config['comm4_time2'] =23;
            }
            // 1点-6点之前不发放
            if (date("H") < $config['comm4_time1'] || date("H") > $config['comm4_time2']) {
                $data['msg'] = '只在'. $config['comm4_time1'] .'点-' .$config['comm4_time2'] . '点之间发放';
                $data['status'] = '10';
                $insertid = db_insert(t_commshare, $data);
                $result['errcode'] = 1;
                $result['msg'] = '很遗憾未摇到,感谢支持!';
                return $result;
            }


            //员工是否有红包
            if ($config['comm4worker'] == 1) {
                $myworker = Worker::getThemeWorkerByOpenid($_G['openid'], $themeid, 1);
                if (!empty($myworker) && $myworker['level']<=3) {
                    $data['msg'] = '员工裂变红包关闭';
                    $data['status'] = '11';
                    $insertid = db_insert(t_commshare, $data);
                    $result['errcode'] = 5;
                    $result['msg'] = '员工不可参与摇一摇,感谢支持!';
                    return $result;
                }
            }


            //判断付款的客户才有红包
            if ($config['comm4ispay'] == 1) {
                $themyrecord = Record::getLastGroupByUid($_G['member']['uid'], $themeid);
                if (empty($themyrecord)) {
                    $data['msg'] = '只有付款后才可以摇一摇';
                    $data['status'] = '12';
                    $insertid = db_insert(t_commshare, $data);
                    $result['errcode'] = 5;
                    $result['msg'] = '很遗憾只有付款后才可以摇一摇,感谢支持!';
                    return $result;
                }
            }

            $fansinfo = db_find('SELECT addtime,islock FROM ' . tablename(t_fans) . "
				WHERE uid ='{$fuid}'");
            if ($fansinfo['islock'] == 1) {
                $data['msg'] = '用户已锁定，无法领裂变红包';
                $data['status'] = '12';
                $insertid = db_insert(t_commshare, $data);
                return $result;
            }
            //10秒内刷新2次以上被锁定
            $sql = 'SELECT count(*) FROM ' . tablename(t_commshare) . "
				WHERE uid ='{$fuid}' and addtime > ";
            $sql10 = TIMESTAMP - 10;
            $sharenum10 = (int)db_fetchcolumn($sql . $sql10);
            $sql120 = TIMESTAMP - 120;
            $sharenum120 = (int)db_fetchcolumn($sql . $sql120);
            $sql3600 = TIMESTAMP - 3600;
            $sharenum3600 = (int)db_fetchcolumn($sql . $sql3600);
            if ($sharenum10 >= 3 || $sharenum120 >= 10 || $sharenum3600 >= 30) {
                $lockstatus = Comm::lockfans($fuid,$_G['openid']);
                if ($lockstatus) {
                    $data['msg'] = '短时间内多次摇一摇被封';
                    $data['status'] = '2';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }

            //打开链接10秒内分享朋友圈,自动锁定
            $addtime2 = TIMESTAMP - $config['comm4yaotime'];
            if ($fansinfo['addtime'] > $addtime2 || $fansinfo['islock'] == 1 || empty($fansinfo)) {
                $lockstatus = Comm::lockfans($fuid,$_G['openid']);
                if ($lockstatus) {
                    $data['msg'] = '链接打开' . $addtime2 . '秒内摇一摇被封';
                    $data['status'] = '2';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }


            //检测时间
            if (!empty($config['comm4time'])) {
                $comm4time = Comm::getCommshareTime($themeid, $fuid);
                if ($comm4time < $config['comm4time']) {
                    $data['msg'] = '离下次摇一摇还有' . ($config['comm4time'] - $comm4time) . '分钟';
                    $data['status'] = '5';
                    $insertid = db_insert(t_commshare, $data);
                    $result['errcode'] = 5;
                    $result['msg'] = $data['msg'];
                    return $result;
                }
            }

            //检测3小时内成交数与发红包数是否达到要求
            if (!empty($config['comm4type']) || !empty($config['comm4typehb'])) {
                $status = Comm::gethourslimit($themeid, $config['comm4type'], $config['comm4typehb']);
                if ($status['error'] == 1) {
                    $data['msg'] = $status['msg'];
                    $data['status'] = '8';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }

            //裂变红包超出收入
            if ($config['comm4zhanbi'] > 0) {
                $Numhour = floatval(Comm::getCommshareNumZhanbi($themeid));
                if ($Numhour > $config['comm4zhanbi']) {
                    $data['msg'] = '裂变红包超出收入的' . $config['comm4zhanbi'] . '%，暂停发放';
                    $data['status'] = '3';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }

            //检测今日已领的个数
            $comm4daynum = Comm::getCommshareToday($themeid, $fuid);
            if ($comm4daynum >= $config['comm4daynum']) {
                $data['msg'] = '今天只可摇' . $config['comm4daynum'] . '个红包';
                $data['status'] = '6';
                $insertid = db_insert(t_commshare, $data);
                $result['errcode'] = 5;
                $result['msg'] = $data['msg'];
                return $result;
            }

            //检测已领的总个数
            $comm4sum = Comm::getCommshareAll($themeid, $fuid);
            if ($comm4sum >= $config['comm4sum']) {
                $data['msg'] = '您总计可摇' . $config['comm4sum'] . '个红包';
                $data['status'] = '7';
                $insertid = db_insert(t_commshare, $data);
                $result['errcode'] = 5;
                $result['msg'] = $data['msg'];
                return $result;
            }

            //检测每小时限额
            $Numhour = floatval(Comm::getCommshareNumHour($themeid));
            if ($Numhour >= floatval($config['comm4hour'])) {
                $data['msg'] = '红包达小时上限';
                $data['status'] = '3';
                $insertid = db_insert(t_commshare, $data);
                return $result;
            }


            //检测每天限额
            $NumDay = floatval(Comm::getCommshareNumDay($themeid));
            if ($NumDay >= floatval($config['comm4day'])) {
                $data['msg'] = '今日红包已发完';
                $data['status'] = '3';
                $insertid = db_insert(t_commshare, $data);
                return $result;
            }

            //检测同一IP
            if (!empty($config['comm4ip'])) {
                $NumIp = floatval(Comm::getCommshareNumIp($themeid, $ClientIp));
                if ($NumIp >= floatval($config['comm4ip'])) {
                    $data['msg'] = '同一网络到上限';
                    $data['status'] = '4';
                    $insertid = db_insert(t_commshare, $data);
                    return $result;
                }
            }

            if ($config['locationtype'] == 1) {
                $City = Comm::getCityDW($GLat, $GLng, $config['comm4city']);
            } else {
                $City = Comm::getCity($system, $ClientIp, $config['comm4city']);
            }
            $data['city'] = $City['city'];
            //根据IP检测地区
            if (!empty($config['comm4city']) && $City['status'] == 0) {
                $data['msg'] = '不在活动地区';
                $data['status'] = '2';
                $insertid = db_insert(t_commshare, $data);
                return $result;
            }

            $insertid = db_insert(t_commshare, $data);

            $totalpayfee = Order::getRealByThemeIdcomm4($themeid) - $data['fee'];
            if ($totalpayfee < 0) {
                $data['msg'] = '您的余额不足,请联系客服进行充值';
                Comm::add_share_comm($data);
                return $result;
            } else {
                $result['errcode'] = 2;
                $result['fee'] = $randomfee;
                $result['msg'] = '恭喜您获得红包' . $randomfee . '元,链接分享至朋友圈即可提现确定';
                return $result;
            }

        }
        elseif ($op == "pyq") {
            $isfahongbao = 1;
            $randomfee = 0;
            if ($isfahongbao == 1) {
                $weizhifulist = db_find('SELECT city,fee FROM ' . tablename(t_commshare) . "
					WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'");
                $weizhifu = $weizhifulist['fee'];
                if ($weizhifu >= 0.3 || ($system['send_mode']==1 && $weizhifu > 0) || ($config['comm4autored'] == 3 && $weizhifu > 0)) {

                    $ordersn = getMillisecond();
                    $data = array(
                        'uniacid' => $_G['mpid'],
                        'themeid' => $themeid,
                        'recordid' => '',
                        'ordersn' => $ordersn,
                        'type' => 7,
                        'uid' => $fuid,
                        'openid' => $_G['openid'],
                        'addtime' => TIMESTAMP,
                        'fee' => $weizhifu,
                        'ip' => $ClientIp,
                        'city' => $weizhifulist['city'],
                        'fromuid' => 0,
                        'status' => 0,
                    );
                    $data2 = $data;
                    $data2['software'] = MODULE_NAME;
                    $insertid = db_insert('2019comm_list', $data2);

                    //1分钟内只能收到一个红包
                    if (empty($weizhifulist['addtime'])) {
                        $addtime = TIMESTAMP - 60;
                    } else {
                        $addtime = $weizhifulist['addtime'] - 60;
                    }
                    $p = array(':themeid' => $data['themeid'], ':uid' => $data['uid'], ':type' => $data['type'], ':addtime' => $addtime);
                    $sql = "SELECT * FROM " . tablename(t_comm) . " WHERE themeid= :themeid and uid= :uid and type= :type and addtime > :addtime";
                    $commrow = db_find($sql, $p);
                    if (!empty($commrow)) {
                        db_query("UPDATE " . tablename(t_commshare) . " SET status = 5, msg = '操作频繁：1分钟内只能收到一个红包'
					WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'");
                        $result['errcode'] = 5;
                        $result['msg'] = '感谢支持';
                        return $result;
                    } else {
                        //将所有未支付记录更新为正常
                        db_query("UPDATE " . tablename(t_commshare) . " SET status = 1, sendtime = " . TIMESTAMP . "
					WHERE themeid = '{$themeid}' and status = 0 and uid ='{$fuid}'");
                    }


                    if ($system['autored'] == 0 || $config['comm4autored'] == 0 || ($config['comm4autored'] == 2 && TIMESTAMP > $config['comm4autoredtime'])) {
                        $data['msg'] = '等待管理员发红包';
                        Comm::add_share_comm($data);
                        $comm4tips = str_replace("#fee", $weizhifu, $config['comm4tips']);
                        $result['errcode'] = 5;
                        $result['msg'] = $comm4tips;
                        $result['fee'] = $randomfee;
                        $result['fee2'] = $weizhifu;
                        return $result;
                    }

                    if ($config['comm4autored'] == 3) {
                        $data['msg'] = '待客户提现';

                        $pm = array(":themeid" => $themeid, ":openid" => $_G['openid']);
                        $totalfail = (float)db_fetchcolumn('SELECT sum(fee) FROM ' . tablename(t_comm) . ' as m 
				            WHERE m.themeid = :themeid and status=0 and type<>99 and m.openid = :openid', $pm);
                        $totalsuccess = (float)db_fetchcolumn('SELECT sum(fee) FROM ' . tablename(t_comm) . ' as m 
			            WHERE m.themeid = :themeid and (status=1 or status=0 and type=99) and m.openid = :openid', $pm);

                        $chae = $config['hbtixian'] - $totalfail - $weizhifu;
                        if ($chae < 0 || ($totalsuccess > 0 && $config['hbtixianmode'] == 0)) {
                            $comm4tips = "恭喜您获得红包" . $weizhifu . "元，可在【我的红包】中提现";
                        } else {
                            $comm4tips = "恭喜您获得红包" . $weizhifu . "元，再有" . $chae . "元就可提现了";
                        }
                        $result['errcode'] = 5;
                        $result['msg'] = $comm4tips;
                        Comm::add_share_comm($data);
                        return $result;
                    }

                    $totalpayfee = Order::getRealByThemeIdcomm4($themeid) - $data['fee'];
                    if ($totalpayfee < 0) {
                        $data['msg'] = '您的余额不足,请联系客服进行充值';
                        Comm::add_share_comm($data);
                        return $result;
                    }

                    Comm::add_share_comm($data);

                    $row = Comm::getCommyaoyiyao($data);
                    $r = array();
                    if (!empty($row) && $row['fee'] >= 0.3 || ($system['send_mode']==1 && $row['fee'] > 0)) {
                        $settings = "commid:" . $row['id'];
                        $r = Fee::commRecord($row, $system);
                        if ($r[0] == 0) {
                            $result['errcode'] = 2;
                            $result['fee'] = $row['fee']; //$randomfee;
                            $result['fee2'] = $row['fee']; //$weizhifu;
                            $result['msg'] = '恭喜您,红包到账' . $row['fee'] . '元';
                            return $result;
                        } else {
                            $result['errcode'] = 3;
                            $result['fee'] = $row['fee']; //$randomfee;
                            $result['fee2'] = $row['fee']; //$weizhifu;
                            $result['msg'] = '恭喜您获得红包' . $row['fee'] . '元';
                            return $result;
                        }
                    } else {
                        $result['errcode'] = 1;
                        $result['msg'] = '感谢支持!';
                        return $result;
                    }
                } else {
                    $result['errcode'] = 1;
                    $result['msg'] = '感谢支持!';
                    return $result;
                }
            } else {
                $result['errcode'] = 1;
                $result['msg'] = '感谢支持!';
                return $result;
            }
        }
    }

    /**
     * Desc:红包雨提现判断
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/5/11 15:40
     * @param $config
     * @return float
     */
     static function redRain()
    {
        global $_G, $_P;
        $op = !empty($_P['op']) ? $_P['op'] : 'display';
        $themeid = intval($_P['themeid']);
        $theme = Theme::getThemeById($themeid);
        $config = Theme::getConfig($themeid);
        $fuid = $_G['member']['uid'];
        $result = array();
        $GLat = $_P['GLat'];
        $GLng = $_P['GLng'];
        $ClientIp = $_G['clientip'];

        $workerid = intval($_P['wid']) > 0 ? intval($_P['wid']) : intval($_P['workerid']);
        $theyworker = Worker::getThemeWorkerByUid($workerid, $themeid, 1);
        if (empty($theyworker)) {
            $workerid = 0;
        } elseif ($theyworker['comm4status'] > 1) {
            $workerid = 0;
        } elseif ($config['comm4typeyg'] > 0) {
            $liulan = 0;
            $chengjiao = 0;
            switch ($config['comm4typeyg']) {
                case '1':
                    $liulan = 30;
                    break;
                case '2':
                    $liulan = 40;
                    break;
                case '3':
                    $liulan = 50;
                    break;
                case '4':
                    $liulan = 60;
                    break;
                case '5':
                    $liulan = 70;
                    break;
                case '6':
                    $chengjiao = 5;
                    break;
                case '7':
                    $chengjiao = 10;
                    break;
                case '8':
                    $chengjiao = 15;
                    break;
                case '9':
                    $chengjiao = 20;
                    break;
                case '10':
                    $chengjiao = 25;
                    break;
                case '11':
                    $chengjiao = 30;
                    break;
                case '12':
                    $chengjiao = 40;
                    break;
                case '13':
                    $chengjiao = 50;
                    break;
            }
            if ($theyworker['forward'] > 500) {
                if ($liulan > 0) {
                    if (($theyworker['forward'] / $theyworker['scansum'] * 100) > $liulan) {
                        db_query("UPDATE " . tablename(t_worker) . " SET comm4status = 2 WHERE uid ='{$workerid}'");
                        $workerid = 0;
                    }

                } elseif ($chengjiao > 0) {
                    $cjtotal = (int)db_fetchcolumn('SELECT COUNT(*) FROM ' . tablename(t_record) . "
					WHERE status > 0 and workerid = '{$workerid}' and themeid = '{$themeid}' ");
                    if ($theyworker['forward'] / $cjtotal > $chengjiao) {
                        db_query("UPDATE " . tablename(t_worker) . " SET comm4status = 2 WHERE uid ='{$workerid}'");
                        $workerid = 0;
                    }
                }
            }
        }
        if (empty($workerid)) {
            $data['msg'] = '没有员工信息，不可领红包';
            $data['status'] = '9';
            $insertid = db_insert(t_commshare, $data);

            $result = array(
                "code" => 5,
                "msg" => '没有员工信息，操作中断!',
            );
            return $result;
        }
        //失败的提示
        $result['code'] = 5;
        $result['msg'] = '很遗憾,无法提现!';
        //在服务器别的软件领过的不可以领
        if ($config['comm4dashuju'] == 0) {
            $status = Comm::gethistorycomm($themeid);
            if ($status['error'] == 1) {
                $data['msg'] = $status['msg'];
                $data['status'] = '8';
                $insertid = db_insert(t_commshare, $data);
                $result['msg'] = '已参与过其他活动,操作中断!';
                return $result;
            }
        }
        // 1点-6点之前不发放
        if (date("H") < $config['comm4_time1'] || date("H") > $config['comm4_time2']) {
            $data['msg'] = '只在'. $config['comm4_time1'] .'点-' .$config['comm4_time2'] . '点之间发放';
            $data['status'] = '10';
            $insertid = db_insert(t_commshare, $data);
            $result['code'] = 1;
            $result['msg'] = '当前时间异常,操作中断!';
            return $result;
        }
        $fansinfo = db_find('SELECT addtime,islock FROM ' . tablename(t_fans) . "
				WHERE uid ='{$fuid}'");
        if ($fansinfo['islock'] == 1) {
            $data['msg'] = '用户已锁定，无法领裂变红包';
            $data['status'] = '12';
            $insertid = db_insert(t_commshare, $data);
            $result['msg'] = '用户已锁定,操作中断!';
            return $result;
        }
        //检测同一IP
        if (!empty($config['comm4ip'])) {
            $NumIp = floatval(Comm::getCommshareNumIp($themeid, $ClientIp));
            if ($NumIp >= floatval($config['comm4ip'])) {
                $data['msg'] = '同一网络到上限';
                $data['status'] = '4';
                $insertid = db_insert(t_commshare, $data);
                $result['msg'] = '同一网络到上限,操作中断!';
                return $result;
            }
        }
        return ['code'=>0,'msg'=>''];
    }
}